package deibay.client;


import java.util.List;
import java.util.Vector;
import org.jdom.Document;
import org.jdom.Element;

import deibay.XmlIO;
import deibay.network.ServerAddress;

public class ServersList {

	private Element root = null;
	private Document doc = null;
	private Vector<ServerAddress> servers = null;
	
	public ServersList()
	{
		servers = new Vector<ServerAddress>();
		loadXmlServersList();
	}
			
	private void createXml()
	{	
		doc = new Document();
		root = new Element("ServersList");
		doc.setRootElement(root);		
	}
	
	private void loadXmlServersList()
	{		
		doc = XmlIO.readXML(XmlIO.LIST_PATH+XmlIO.XML_FILE);
		if(doc == null)
		{
			createXml();
			XmlIO.writeXmltoFile(doc, XmlIO.LIST_PATH+XmlIO.XML_FILE);
			doc = XmlIO.readXML(XmlIO.LIST_PATH+XmlIO.XML_FILE);
		}
		root = doc.getRootElement();
		getServers();
	}
	
	private void getServers()
	{
		List<Element> elements = root.getChildren();
		for(Element e: elements)
		{
			String ip = e.getChild("ip").getValue();
			int port = Integer.parseInt(e.getChild("port").getValue());
			servers.add(new ServerAddress(ip, port));
		}
	}
	
	public ServerAddress getServer(int i)
	{
		return servers.get(i);
	}
	
	public int getServersCount()
	{
		return this.servers.size();
	}
}
